//
//  DebugTools.m
//  Tools
//
//  Created by han on 2019/1/18.
//  Copyright © 2019 han. All rights reserved.
//

#import "DebugTools.h"
@interface DebugTools ()

@property (nonatomic, strong) CADisplayLink *displayLink;

@property (nonatomic, assign) NSTimeInterval lastTimestamp;

@property (nonatomic, assign) NSInteger performTimes;

@end
@implementation DebugTools
static DebugTools *instance = nil;
+ (instancetype)shareManager {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[DebugTools alloc]init];
    });
    return instance;
}

- (void)startMonitoring {
    _displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(displayLinkTicks:)];
    [_displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
}

- (void)displayLinkTicks:(CADisplayLink *)link {
    if (_lastTimestamp == 0) {
        _lastTimestamp = link.timestamp;
        return;
    }
    _performTimes ++;
    NSTimeInterval interval = link.timestamp - _lastTimestamp;
    if (interval < 1) { return; }
    _lastTimestamp = link.timestamp;
    float fps = _performTimes / interval;
    _performTimes = 0;
    if (self.valueBlock) {
        self.valueBlock(fps);
    }
}

- (void)stopMonitoring {
    [_displayLink invalidate];
}

@end
@interface FpsShow()
@property (nonatomic, strong) UILabel *fpsLabel;
@end
@implementation FpsShow

- (void)showFps {
//    self.fpsLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 500, kScreen_Width/3, 30)];
//    self.fpsLabel.backgroundColor = [UIColor greenColor];
//    [[UIApplication sharedApplication].keyWindow addSubview:self.fpsLabel];
//    [[UIApplication sharedApplication].keyWindow bringSubviewToFront:self.fpsLabel];
//    self.fpsLabel.text = @"0fps";
//    DebugTools *tools = [DebugTools shareManager];
//    tools.valueBlock = ^(CGFloat value) {
//        _fpsLabel.text = [NSString stringWithFormat:@"%.0f fps",value];
//    };
//    [tools startMonitoring];
}

+ (void)showFpsInWindow {
    FpsShow *fps = [[FpsShow alloc]init];
    [fps showFps];
}

@end
